package com.example.sharesinfo.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.helper.GlideHelper;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.view.InputTextMsgDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

public class QADetailActivity extends BaseUIActivity implements View.OnClickListener {
    private static final String LOGTAG = "QADetailActivity:";
    //返回json的字符串来处理
    private String response;
    private ImageButton ib_back;
    private TextView tv_question_content;
    private TextView tv_ask_username;
    private TextView tv_question_time;
    private CircleImageView ci_answer_image;
    private TextView tv_answer_username;
    private TextView tv_answer_time;
    private CheckBox cb_focus;
    private TextView tv_answer_content;
    private LinearLayout ll_answer;
    private LinearLayout ll_put_answer;
    private RelativeLayout rl_userInfo;
    private Button btn_answer;
    //评论弹框
    private InputTextMsgDialog inputTextMsgDialog;
    private String userId;
    private String qusetionId;
    //处理返回code
    private static final int SENDANSWERSUCCESS = 1001;
    private static final int SENDANSWERFAILED = 1002;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case SENDANSWERSUCCESS:
                    rl_userInfo.setVisibility(View.VISIBLE);
                    ll_answer.setVisibility(View.VISIBLE);
                    ll_put_answer.setVisibility(View.GONE);
                    GlideHelper.loadUrl(QADetailActivity.this, SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, ""), ci_answer_image);
                    tv_answer_username.setText(SpUtils.getInstance().getString(Constants.SP_USER_NAME, ""));
                    tv_answer_time.setText("刚刚");
                    tv_answer_content.setText(msg.obj.toString());
                    Toast.makeText(QADetailActivity.this, "回答成功", Toast.LENGTH_SHORT).show();
                    break;
                case SENDANSWERFAILED:
                    Toast.makeText(QADetailActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
            }
            return false;
        }
    });

    public static void startActivity(Context mContext, String response) {
        Intent intent = new Intent(mContext, QADetailActivity.class);
        intent.putExtra("response", response);
        mContext.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qadetail);
        initView();
        analyzeResponse(response);
    }

    private void initView() {
        userId = SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        response = getIntent().getStringExtra("response");
        ib_back = findViewById(R.id.ib_back);
        ib_back.setOnClickListener(this);
        tv_question_content = findViewById(R.id.tv_question_content);
        tv_ask_username = findViewById(R.id.tv_ask_username);
        tv_question_time = findViewById(R.id.tv_question_time);
        ci_answer_image = findViewById(R.id.ci_answer_image);
        tv_answer_username = findViewById(R.id.tv_answer_username);
        tv_answer_time = findViewById(R.id.tv_answer_time);
        cb_focus = findViewById(R.id.cb_focus);
        tv_answer_content = findViewById(R.id.tv_answer_content);
        ll_answer = findViewById(R.id.ll_answer);
        ll_put_answer = findViewById(R.id.ll_put_answer);
        rl_userInfo = findViewById(R.id.rl_userInfo);
        btn_answer = findViewById(R.id.btn_answer);
        btn_answer.setOnClickListener(this);
        inputTextMsgDialog = new InputTextMsgDialog(this, R.style.customdialogstyle);
        inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
            @Override
            public void onTextSend(String msg) {
                LogUtils.i(LOGTAG + msg);
                sendAnswer(qusetionId, userId, msg);
                //queryDatas();
            }
        });
    }

    /**
     * R
     * 解析传来的json字符串
     */
    public void analyzeResponse(String json) {
        try {
            JSONObject object = new JSONObject(json);
            JSONObject data = object.getJSONObject("data");
            LogUtils.i(LOGTAG + data);
            //传递用户问题信息
            if (data.has("QuestionId")) {
                qusetionId = data.getString("QuestionId");
            } else {
                qusetionId = data.getString("Id");
            }

            tv_question_content.setText(data.getString("QuestionContent"));
            tv_ask_username.setText(data.getString("Ask_Username"));
            tv_question_time.setText(data.getString("QuestionTime"));
            if (data.has("AnswerContent")) {
                LogUtils.i(LOGTAG + "有回答");
                rl_userInfo.setVisibility(View.VISIBLE);
                ll_answer.setVisibility(View.VISIBLE);
                ll_put_answer.setVisibility(View.GONE);
                GlideHelper.loadUrl(this, data.getString("Answer_ImageUrl"), ci_answer_image);
                tv_answer_username.setText(data.getString("Answer_Username"));
                tv_answer_time.setText(data.getString("AnswerTime"));
                tv_answer_content.setText(data.getString("AnswerContent"));
            } else {
                rl_userInfo.setVisibility(View.GONE);
                ll_answer.setVisibility(View.GONE);
                ll_put_answer.setVisibility(View.VISIBLE);
                LogUtils.i(LOGTAG + "没有回答");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回答该问题
     * QuestionId=1&
     * UserId=12
     * AnswerContent:必须大于15个字
     * post
     */
    public void sendAnswer(String QuestionId, String UserId, String AnswerContent) {
        String urlRoot = "http://119.23.221.142/api/user/SendAnswer?";
        Map<String, String> datas = new HashMap<>();
        datas.put("QuestionId", QuestionId);
        datas.put("UserId", UserId);
        datas.put("AnswerContent", AnswerContent);
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    Message message = mHandler.obtainMessage();

                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        JSONObject object = new JSONObject(s);
                        if (object.getString("code").equals("200")) {
                            //回答成功
                            JSONObject result = object.getJSONObject("data");
                            message.what = SENDANSWERSUCCESS;
                            message.obj = result.getString("AnswerContent");
                            mHandler.sendMessage(message);
                        } else {
                            //回答失败
                            message.what = SENDANSWERFAILED;
                            message.obj = object.getString("message");
                            mHandler.sendMessage(message);
                        }
                        LogUtils.i(LOGTAG + s);
                    }

                    @Override
                    public void OnFailed(String s) {
                        message.what = 404;
                        message.obj = s;
                        mHandler.sendMessage(message);
                    }
                });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.btn_answer:
                inputTextMsgDialog.show();
                break;
        }
    }
}
